package com.baoxin.chenxixc4coach;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

public class H5TestActivity extends BaseActivity {

    private View mRootView;
    private WebView webView;
    private ProgressBar progressBar;
    private EditText mCommentEdit;
    private LinearLayout mShowEdit;
    private LinearLayout mEditLL;

    public static void startAction(Context context, String url) {
        Intent intent = new Intent(context, H5TestActivity.class);
        intent.putExtra("URL", url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_h5_test);
        mRootView = findViewById(R.id.root_view);
        progressBar = findViewById(R.id.progress);
        mCommentEdit = findViewById(R.id.comment_content);
        mShowEdit = findViewById(R.id.comment_ll);
        mEditLL = findViewById(R.id.edit_ll);

        webView = findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(webChromeClient);
        //    webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");
        webView.addJavascriptInterface(this, "AndroidWebView");
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        Map<String, String> header = new HashMap<>();
        header.put("token", MyApplication.getToken());
        webView.loadUrl(getIntent().getStringExtra("URL"), header);

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();
        }
        return super.onKeyDown(keyCode, event);
    }


    @JavascriptInterface
    public void commentResult(String result) {
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void canComment() {

        webView.post(new Runnable() {
            @Override
            public void run() {
                //显示可评论bottom
                mShowEdit.setVisibility(View.VISIBLE);


            }
        });
    }


    public void clickEdit(View view) {
        mEditLL.setVisibility(View.VISIBLE);//必须在前，不然弹不出软键盘
        mCommentEdit.setFocusable(true);
        mCommentEdit.setFocusableInTouchMode(true);
        mCommentEdit.requestFocus();

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mCommentEdit, InputMethodManager.SHOW_IMPLICIT);


        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);

    }

    //发送评论
    public void onSubmitComment(View view) {
        String content = mCommentEdit.getText().toString();
        if (content.length() == 0) {
            return;
        }
        //android4.4以上
        webView.evaluateJavascript("_submit('" + content + "')", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {

            }
        });

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //判断窗口可见区域大小
            Rect r = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
            int screenHeight = getResources().getDisplayMetrics().heightPixels;
            int heightDifference = screenHeight - (r.bottom - r.top);
            boolean isKeyboardShowing = heightDifference > screenHeight / 3;
            if (isKeyboardShowing) {
                mEditLL.setVisibility(View.VISIBLE);
                mShowEdit.setVisibility(View.GONE);
            } else {
                mEditLL.setVisibility(View.GONE);
                mShowEdit.setVisibility(View.VISIBLE);
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        //释放资源
        webView.destroy();
        webView = null;
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }

    };


}
